package com.ap.core.dao.impl;

import com.ap.core.dao.AbstractAPCoreBaseJpaDao;
import com.ap.core.dao.AbstractReadOnlyAPCoreBaseJpaDao;
import com.ap.core.dao.ReconciliationParameterDao;
import com.ap.core.domain.ReconciliationParameter;
import org.hibernate.criterion.Order;
import org.joda.time.LocalDateTime;

import java.util.List;

/**
 * User: Ranjit.Singh
 */
public class JpaReconciliationParameterDao extends AbstractReadOnlyAPCoreBaseJpaDao<ReconciliationParameter, String> implements ReconciliationParameterDao {

    @Override
    public ReconciliationParameter findById(String primaryKey) {
        return findById(ReconciliationParameter.class, primaryKey);
    }

    @Override
    public ReconciliationParameter getCurrentCycle(final LocalDateTime currentDateTime) {
        final List<ReconciliationParameter> reconciliationParameters = getSession().createCriteria(ReconciliationParameter.class).addOrder(Order.asc("id")).list();
        if (null == reconciliationParameters || reconciliationParameters.isEmpty()) {
            throw new RuntimeException("No meta data is specified for reconciliation id generation");
        }
        for(ReconciliationParameter reconciliationParameter: reconciliationParameters){
             if(currentDateTime.getMillisOfDay() > reconciliationParameter.getCycleStartTimeStmp().getMillisOfDay() &&
                        currentDateTime.getMillisOfDay() <= reconciliationParameter.getCycleEndTimeStmp().getMillisOfDay()){
                 return reconciliationParameter;
             }
        }
        throw new RuntimeException("No meta data found for reconciliation id generation at time :" + currentDateTime);
    }

}
